package com.example.index

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.res.Configuration
import android.os.Build
import android.os.LocaleList
import android.util.Log
import com.example.index.arch.mvvm.AppInjector
import com.example.index.arch.mvvm.di.DaggerAppComponent
import com.example.index.system.LocaleManager
import com.liulishuo.filedownloader.util.FileDownloadHelper
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasActivityInjector
import java.util.*
import javax.inject.Inject

class App : Application(), HasActivityInjector {


    @Inject
    lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity>

    override fun activityInjector(): AndroidInjector<Activity> = dispatchingAndroidInjector

    val TAG = "App"

    companion object Instance {
        lateinit var app: Context
    }

    override fun onCreate() {
        super.onCreate()
        FileDownloadHelper.holdContext(this)

        DaggerAppComponent.builder()
            .build()
            .inject(this)

        AppInjector.initialize(this)

    }


    override fun onConfigurationChanged(newConfig: Configuration?) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Log.i(
                TAG,
                "onConfigurationChanged: ${newConfig?.locales?.all()}  ${newConfig?.locales?.get(0)}"
            )
        }
        super.onConfigurationChanged(newConfig)
    }


    override fun attachBaseContext(base: Context?) {
        LocaleManager.init(base)
        //在启动应用之前，设置全局的语言上下文
        super.attachBaseContext(LocaleManager.createLocaleConfiguredContext(base))
        app = base!!
    }
}

fun LocaleList.all(): ArrayList<Locale> {

    val list = arrayListOf<Locale>()

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        val size = size()
        for (i in 0 until size) {
            list.add(get(i))
        }
    }

    return list
}